package com.ktjy.filter;

import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

public class AuthorizationGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public int getOrder(){
        return -100;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, org.springframework.cloud.gateway.filter.GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("Authorization");
        System.out.println("全局过滤器执行了...检查token是否有效");
        if (!isVaildToken(token)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            String errorMessage="{\"message\":\"Unauthorized:Invalid Token\"}";
            System.out.println("Token无效："+errorMessage);
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(errorMessage.getBytes(StandardCharsets.UTF_8));
            return exchange.getResponse().writeWith(Flux.just(buffer));
        }
        return chain.filter(exchange);
    }
    private boolean isVaildToken(String token){
        return token != null && !token.isEmpty();
    }
}
